package edu.bbu.license.client.android.services.user.worker;

import edu.bbu.license.client.android.communication.exceptions.WrongUserDataException;
import edu.bbu.license.client.android.communication.factory.CLTFactory;
import edu.bbu.license.client.android.communication.model.UserPOJO;
import edu.bbu.license.client.android.communication.services.UserCLTServices;
import edu.bbu.license.client.android.services.BaseService;
import edu.bbu.license.client.android.services.exceptions.IdentificationException;
import edu.bbu.license.client.android.services.exceptions.NetworkException;
import edu.bbu.license.client.android.utility.Crypter;
import edu.bbu.license.client.android.utility.PasswordCreator;

public class SimpleAutentificationService extends BaseService implements AutentificationService {

	private Crypter cryptingService = new Crypter();
	private PasswordCreator passwordGenerator = new PasswordCreator();
	
	private UserCLTServices communicationServices = CLTFactory.getCLTFactory(CLTFactory.THRIFT_FACTORY).getUserCLTServices();
	
	@Override
	public boolean isValidAutentificationData(String username, String password) throws NetworkException {
		UserPOJO user = new UserPOJO(username, cryptingService.encrypt(password));
		
		try {
			communicationServices.logonUser(user);
		} catch (WrongUserDataException e) {
			return false;
		} catch (Exception e) {
			throw new NetworkException("Checking identification data failed, network error.", e);
		}
		
		return true;
	}

	@Override
	public void registerNewUser(String username) throws NetworkException, IdentificationException {
		String password = passwordGenerator.generatePassword(16);
		UserPOJO user = new UserPOJO(username, cryptingService.encrypt(password));

		try {
			communicationServices.registerUser(user);
		} catch (WrongUserDataException e) {
			throw new IdentificationException("Registration failed, e-mail address already in use.", e);
		} catch (Exception e) {
			throw new NetworkException("Registration failed, network error.", e);
		}
	}

	@Override
	public void generateNewPassword(String username) throws NetworkException, IdentificationException {
		String newPassword = passwordGenerator.generatePassword(16);
		UserPOJO user = new UserPOJO(username, "-");

		try {
			communicationServices.forgotPassword(user, cryptingService.encrypt(newPassword));
		} catch (WrongUserDataException e) {
			throw new IdentificationException("Generating password failed, e-mail address doesn't exist.", e);
		} catch (Exception e) {
			throw new NetworkException("Generating password failed, network error.", e);
		}
	}
}
